// 存储最新的分析结果
let lastAnalysisResult = null;

document.addEventListener('DOMContentLoaded', function() {
    const dropZone = document.getElementById('dropZone');
    const videoInput = document.getElementById('videoInput');
    const videoPreview = document.getElementById('videoPreview');
    const videoPlayer = document.getElementById('videoPlayer');
    const videoDuration = document.getElementById('videoDuration');
    const videoSize = document.getElementById('videoSize');
    const analyzeBtn = document.getElementById('analyzeBtn');
    const uploadForm = document.getElementById('uploadForm');

    // 阻止表单默认提交
    uploadForm.addEventListener('submit', (e) => {
        e.preventDefault();
        return false;
    });

    // 点击上传区域触发文件选择
    dropZone.addEventListener('click', () => videoInput.click());

    // 处理文件选择
    videoInput.addEventListener('change', handleFileSelect);

    // 添加分析按钮的点击事件监听
    analyzeBtn.addEventListener('click', (e) => {
        e.preventDefault();
        analyzeVideo();
    });

    // 处理拖放
    dropZone.addEventListener('dragover', (e) => {
        e.preventDefault();
        dropZone.classList.add('dragover');
    });

    dropZone.addEventListener('dragleave', () => {
        dropZone.classList.remove('dragover');
    });

    dropZone.addEventListener('drop', (e) => {
        e.preventDefault();
        dropZone.classList.remove('dragover');
        
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            videoInput.files = files;
            handleFileSelect({ target: videoInput });
        }
    });

    // 视频加载完成后更新时长信息
    videoPlayer.addEventListener('loadedmetadata', function() {
        const duration = videoPlayer.duration;
        const minutes = Math.floor(duration / 60);
        const seconds = Math.floor(duration % 60);
        videoDuration.textContent = `时长：${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    });
});

// 处理文件选择
function handleFileSelect(event) {
    const file = event.target.files[0];
    if (!file) return;

    // 验证文件类型
    const validTypes = ['video/mp4', 'video/avi', 'video/quicktime'];
    if (!validTypes.includes(file.type)) {
        alert('请选择有效的视频文件（MP4, AVI, MOV）');
        return;
    }

    // 验证文件大小（500MB限制）
    if (file.size > 500 * 1024 * 1024) {
        alert('文件大小超过500MB限制');
        return;
    }

    // 更新视频大小显示
    const sizeMB = (file.size / (1024 * 1024)).toFixed(2);
    videoSize.textContent = `大小：${sizeMB} MB`;

    // 预览视频
    const videoPreview = document.getElementById('videoPreview');
    const videoPlayer = document.getElementById('videoPlayer');
    videoPlayer.src = URL.createObjectURL(file);
    videoPreview.style.display = 'block';
}

// 获取服务类型
function getServiceType(selectedType) {
    return 'videoDetection';
}

// 分析视频
async function analyzeVideo() {
    const videoInput = document.getElementById('videoInput');
    const resultArea = document.getElementById('analysisResult');
    const downloadBtn = document.getElementById('downloadBtn');
    const analyzeBtn = document.getElementById('analyzeBtn');

    if (!videoInput.files || videoInput.files.length === 0) {
        alert('请先选择视频文件！');
        return;
    }

    // 显示加载状态
    resultArea.innerHTML = '<div class="loading">分析中...<div class="loader"></div></div>';
    analyzeBtn.disabled = true;
    downloadBtn.style.display = 'none';

    try {
        const formData = new FormData();
        formData.append('video', videoInput.files[0]);
        formData.append('serviceType', 'videoDetection');

        // 发送请求
        const response = await fetch('http://localhost:5000/api/analyze-video', {
            method: 'POST',
            body: formData
        });

        if (!response.ok) {
            throw new Error(`HTTP错误! 状态码: ${response.status}`);
        }

        const data = await response.json();
        
        if (data.code !== 200) {
            throw new Error(data.error || '未知错误');
        }

        // 保存最后的分析结果用于下载
        lastAnalysisResult = data.data;
        
        // 显示结果
        displayResult(data.data);
        downloadBtn.style.display = 'block';

    } catch (error) {
        resultArea.innerHTML = `
            <div class="error">
                <p>分析失败: ${error.message}</p>
                <p>请检查视频格式后重试</p>
            </div>
        `;
    } finally {
        analyzeBtn.disabled = false;
    }
}

// 结果显示调整
function displayResult(result) {
    const safeResult = result || {};
    const riskLevel = (safeResult.RiskLevel || 'none').toLowerCase();
    
    // 风险等级配置
    const riskDetails = {
        high: { color: '#ff4d4f', text: '高风险', icon: '⚠️' },
        medium: { color: '#fa8c16', text: '中风险', icon: '⚠️' },
        low: { color: '#fadb14', text: '低风险', icon: 'ℹ️' },
        none: { color: '#52c41a', text: '无风险', icon: '✅' },
        default: { color: '#666', text: '未知风险', icon: '❓' }
    };

    const currentRisk = riskDetails[riskLevel] || riskDetails.default;

    let resultHTML = `
        <div class="risk-level" style="border-color: ${currentRisk.color}">
            <span style="color: ${currentRisk.color}">
                ${currentRisk.icon} ${currentRisk.text}
            </span>
        </div>

        <div class="section">
            <h3>画面检测结果</h3>
            <div class="summary">
                <p>总帧数：${safeResult.FrameResult?.FrameNum || 0}</p>
                <p>风险等级：${safeResult.FrameResult?.RiskLevel || 'none'}</p>
                ${(safeResult.FrameResult?.FrameSummarys || []).map(summary => `
                    <div class="summary-item">
                        <p>标签：${summary.Label || '无标签'}</p>
                        <p>描述：${summary.Description || '无描述'}</p>
                        <p>出现次数：${summary.LabelSum || 0}</p>
                    </div>
                `).join('')}
            </div>
            <div class="frames">
                ${(safeResult.FrameResult?.Frames || []).map(frame => `
                    <div class="frame-item">
                        <span class="timestamp">${frame.Offset || 0}s</span>
                        <span class="label" style="color: ${getRiskColor(frame.RiskLevel)}">
                            ${frame.RiskLevel || '无风险'}
                        </span>
                        <div class="result-detail">
                            ${frame.Results?.map(result => `
                                <div class="service-result">
                                    <p>检测服务：${result.Service || '未知服务'}</p>
                                    ${result.Result?.map(item => `
                                        <p>描述：${item.Description || '无详细描述'}</p>
                                        <p>标签：${item.Label || '无标签'}</p>
                                    `).join('')}
                                </div>
                            `).join('')}
                        </div>
                        <div class="frame-image">
                            <a href="${frame.TempUrl}" target="_blank">查看截图</a>
                        </div>
                    </div>
                `).join('')}
            </div>
        </div>

        <div class="section">
            <h3>音频检测结果</h3>
            <div class="summary">
                <p>风险等级：${safeResult.AudioResult?.RiskLevel || 'none'}</p>
                ${(safeResult.AudioResult?.AudioSummarys || []).map(summary => `
                    <div class="summary-item">
                        <p>标签：${summary.Label || '无标签'}</p>
                        <p>出现次数：${summary.LabelSum || 0}</p>
                    </div>
                `).join('')}
            </div>
            <div class="slices">
                ${(safeResult.AudioResult?.SliceDetails || []).map(audio => `
                    <div class="audio-item">
                        <div class="time-range">
                            <span class="timestamp">${audio.StartTime || 0}s - ${audio.EndTime || 0}s</span>
                        </div>
                        <span class="label" style="color: ${getRiskColor(audio.RiskLevel)}">
                            ${audio.RiskLevel || '无风险'}
                        </span>
                        <div class="audio-details">
                            <p>识别内容：${audio.Text || '无文本内容'}</p>
                            ${audio.Labels ? `<p>标签：${audio.Labels}</p>` : ''}
                            ${audio.RiskTips ? `<p>风险提示：${audio.RiskTips}</p>` : ''}
                            ${audio.RiskWords ? `<p>风险词：${audio.RiskWords}</p>` : ''}
                            <p><a href="${audio.Url}" target="_blank">播放音频片段</a></p>
                        </div>
                    </div>
                `).join('')}
            </div>
        </div>
    `;

    document.getElementById('analysisResult').innerHTML = resultHTML;
}

// 颜色获取函数
function getRiskColor(level) {
    const colors = {
        high: '#ff4d4f',
        medium: '#fa8c16',
        low: '#fadb14',
        none: '#52c41a',
        default: '#666'
    };
    return colors[(level || 'none').toLowerCase()] || colors.default;
}

// 下载结果功能
function downloadResult() {
    if (!lastAnalysisResult) {
        alert('没有可下载的分析结果');
        return;
    }

    const blob = new Blob(
        [JSON.stringify(lastAnalysisResult, null, 2)], 
        { type: 'application/json;charset=utf-8' }
    );
    
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `视频分析结果_${new Date().toISOString().slice(0,19).replace(/[:-]/g, '')}.json`;
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    URL.revokeObjectURL(link.href);
}

async function pollResult(jobId) {
    const maxRetries = 30;
    const retryInterval = 2000;
    
    for (let i = 0; i < maxRetries; i++) {
        try {
            const response = await fetch(`/api/video-result?job_id=${jobId}`);
            const data = await response.json();
            
            if (data.code === 200) {
                // 处理实际数据结构
                return {
                    RiskLevel: data.data.RiskLevel,
                    Frames: data.data.FrameSummary,
                    Audio: data.data.AudioSummary,
                    Suggestion: data.data.Suggestion
                };
            } else if (data.code === 202) {
                await new Promise(resolve => setTimeout(resolve, retryInterval));
                continue;
            } else {
                throw new Error(data.error || '分析失败');
            }
        } catch (error) {
            if (i === maxRetries - 1) throw error;
            await new Promise(resolve => setTimeout(resolve, retryInterval));
        }
    }
    throw new Error('分析超时');
} 